<template>
  <div class="app-single-image-upload" :style="{height: `${108 + (size ? 26 : 0)}px`}">
    <el-upload list-type="text"
               :limit="1"
               :action="url"
               :http-request="upload"
               :on-success="onSuccess"
               :on-remove="onRemove"
               :file-list="fileList"
               :before-upload="beforeAvatarUpload"
               :show-file-list="true"
               :disabled="disabled"
               accept="wtc"
               name="multipartFile">
      <el-button size="mini" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传{{type}}文件</div>
    </el-upload>
    <!-- <span style="color: red; line-height: 16px;" class="el-upload__tip" :style="{opacity: required && !value ? 1 : 0}">该图片是必须的</span> -->
  </div>
</template>

<script>
  import axios from 'axios'

  export default {
    name:'AppFileUpload',
    props: {
      value: String,
      urlProp: String,
      disabled: {type: Boolean, default: false},
      required: {type: Boolean, default: false},
      size: String,
      type:{type:String}
    },
    data() {
      return {
        url: `${process.env.API_URL_BASE}/commons/attachments/uploadTmp.do`,
        name:'',
      }
    },

    computed: {
      fileList() {
        let that = this
        return _([this.value])
          .compact()
          .map(x => this.urlProp ? x[this.urlProp] : x)
          .map(filename => ({url: this.imageUrl(filename),name:this.name}))
          .value();
      }
    },

    methods: {
      imageUrl(filename) {
        return `${process.env.API_URL_BASE}/files/${filename}`;
      },

      onSuccess(resp) {
        const filename = resp.data.data;
        this.$emit('input', this.urlProp ? {[this.urlProp]: filename} : filename);
        console.log(resp)
      },

      onRemove() {
        this.$emit('input', null);
      },

      upload({action, filename, file, onSuccess}) {
        const form = new FormData();
        form.append(filename, file);
        axios.post(action, form).then(onSuccess)
      },
      beforeAvatarUpload(file) {
//        this.name = file.name
//        const isJPG = file.type === 'image/jpeg';
//        const isLt2M = file.size / 1024 / 1024 < 2;
//
//        if (!isJPG) {
//          this.$message.error('上传头像图片只能是 JPG 格式!');
//        }
//        if (!isLt2M) {
//          this.$message.error('上传头像图片大小不能超过 2MB!');
//        }
//        return isJPG && isLt2M;
      }
    }
  }
</script>

<style lang="scss">
  .app-single-image-upload {
    width: 148px;
    height: 174px;
    >div {
      height: 148px;
      position: relative;
      ul.el-upload-list--picture-card>li {
        z-index: 999;
      }

      .el-upload--picture-card {
        position: absolute;
        top: 0;
        left: 0;
      }
    }
  }
</style>
